package scrape

import (
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"log"
	"nike-scraper/request"
	"nike-scraper/util"
	"regexp"
	"strings"
)

// queryPage 现在返回教师信息的切片
func queryPage(courseURL string, courseName string) []string {
	var teachers []string

	// 创建 GET 请求
	resp := request.SendGetRequest(courseURL)
	defer resp.Body.Close()

	// 解析响应内容
	doc, err := goquery.NewDocumentFromReader(resp.Body)
	if err != nil {
		log.Fatalf("Error parsing response body: %v", err)
	}

	// 将解析后的HTML文档保存到文件
	err = util.SaveHTMLToFile(doc, "resource_example/"+platform+"/"+"course_detail", courseName+".html")
	if err != nil {
		log.Fatalf("Error saving HTML to file: %v", err)
	}

	// 提取教师信息
	doc.Find(".teacher-team-i").Each(func(i int, s *goquery.Selection) {
		// 获取教师名字
		teacherName := s.Find(".teacher-name-text").Text()

		// 获取教师职称，并去除两端的空白字符
		teacherRole := strings.TrimSpace(s.Find(".teacher-role p").Text())

		// 添加教师信息到切片
		teachers = append(teachers, fmt.Sprintf("%s|%s", teacherName, teacherRole))
	})

	// 如果教师信息为空，尝试第二种方式提取教师信息
	if len(teachers) == 0 {

		// 提取staffLectors信息
		doc.Find("script").Each(func(i int, s *goquery.Selection) {
			// 匹配staffLectors信息
			scriptText := s.Text()
			if strings.Contains(scriptText, "window.staffLectors") {
				// 解析出staffLectors数组中的信息
				re := regexp.MustCompile(`lectorName\s*:\s*"([^"]+)"\s*,\s*lectorTitle\s*:\s*"([^"]+)"`)
				matches := re.FindAllStringSubmatch(scriptText, -1)
				for _, match := range matches {
					if len(match) == 3 {
						teachers = append(teachers, fmt.Sprintf("%s|%s", match[1], match[2]))
					}
				}
			}
		})
	}

	return teachers
}
